package com.juc.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 有返回值的 supplyAsync 异步回调
 * ajax，成功和失败的回调，返回的是错误信息；
 */
public class Demo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture =
                CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
                    int i = 10 / 0;
                    return 1024;
                });
        System.out.println(completableFuture.whenComplete((t, u) -> {
            // 正常的返回结果
            System.out.println("t=>" + t);
            // 错误信息：java.util.concurrent.CompletionException:java.lang.ArithmeticException: /by zero
            System.out.println("u=>" + u);
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 512; // 可以获取到错误的返回结果
        }).get());

    }
}
